<template>
  <div>
    <el-dialog :title="showTitle" :visible="dialogVisible" @close="close">
      <el-form ref="addDept" label-width="120px" :model="formData" :rules="rules">
        <el-form-item prop="deptName" label="部门名称">
          <el-input v-model="formData.deptName" placeholder="2-10个字符" size="mini" style="width: 80%" />
        </el-form-item>
        <el-form-item prop="leader" label="部门负责人">
          <el-select v-model="formData.leader" placeholder="请选择负责人" size="mini" style="width: 80%">
            <el-option
              v-for="item in managerList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="phone" label="负责人电话">
          <el-input v-model="formData.phone" placeholder="请输入联系电话" size="mini" style="width: 80%" />
        </el-form-item>
        <el-form-item prop="description" label="部门介绍">
          <el-input v-model="formData.description" placeholder="1-100个字符" type="textarea" size="mini" :rows="4" style="width: 80%" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12" />
            <el-button type="primary" size="mini" @click="btnOk">保存</el-button>
            <el-button size="mini" @click="close">取消</el-button>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartmentList, getUserList, addDepartment, getDepartById, updateDepartment } from '@/api/department'

export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    currentNodeId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      managerList: [],
      formData: {
        deptName: '',
        leader: '',
        phone: '',
        description: '',
        parentId: '',
        orderNum: 0
      },
      rules: {
        deptName: [{ required: true, message: '部门名称不能为空', trigger: 'blur' },
          {
            min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'
          }, {
            trigger: 'blur',
            // 自定义校验模式
            validator: async(rule, value, callback) => {
            // value就是输入的编码
              const result = await getDepartmentList()
              let dataArray = Object.values(result.data)
              // 判断是不是编辑状态，如果是编辑状态，则排除自己
              if (this.formData.deptId) {
                dataArray = dataArray.filter(item => item.deptId !== this.formData.deptId)
              }
              if (dataArray.some(item => item.deptName === value)) {
                callback(new Error('部门中已经有该名称了'))
              } else {
                callback()
              }
            }
          }],
        leader: [{ required: true, message: '负责人不能为空', trigger: 'blur' }],
        phone: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '部门描述不能为空', trigger: 'blur' }]
      }

    }
  },
  computed: {
    showTitle() {
      return this.formData.deptId ? '编辑部门' : '新增部门'
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    close() {
      this.formData = {
        deptName: '',
        leader: '',
        phone: '',
        description: '',
        parentId: '',
        orderNum: 0
      }
      // 关闭弹窗时，重置表单
      this.$refs.addDept.resetFields()
      this.$emit('update:dialogVisible', false)
    },
    async getUserList() {
      const result = await getUserList()
      this.managerList = Object.values(result.rows)
    },
    btnOk() {
      this.$refs.addDept.validate(
        async isOk => {
          if (isOk) {
            let message = '添加'
            // 如果是编辑状态，则更新
            if (this.formData.deptId) {
              console.log(this.formData)
              await updateDepartment(this.formData)
              message = '更新'
            } else {
              await addDepartment({ ...this.formData, parentId: this.currentNodeId })
            }
            this.$message.success(`${message}成功`)
            this.$emit('updateDepart')
            this.close()
          }
        }
      )
    },
    async getDeptById(id) {
      const result = await getDepartById(id)
      this.formData = result.data
    }
  }
}
</script>
